-- repeat_until_finish
--
local import = import
---@type behavior_ret
local bret = import('bt/bt_plugin/behavior3/behavior_ret')

local M = {
    name = "RepeatUntilFinish",
    type = "Composite",
    desc = "直到完成",
    args = {
        --{ name = "str", type = "string", desc = "变量描述" }
    },
    doc = [[
        + 并行运行所有子节点直到没有running返回
    ]]
}

function M.run(node, env, value)
    local count = 0
    local last, last_ret = node:resume(env)
    local level = #env.stack
    last = last or {}

    for i = 1, #node.children do
        local status = nil
        local child = node.children[i]
        local nodes = last[i]
        if nodes and #nodes > 0 then
            while #nodes > 0 do
                child = table.remove(nodes)
                env:push_stack(child)
                status = child:run(env)
                if status == bret.RUNNING then
                    local p = #nodes + 1
                    while #env.stack > level do
                        table.insert(nodes, p, env:pop_stack())
                    end
                    break
                end
            end
        else
            nodes = nil
            status = child:run(env)
        end

        if status == bret.RUNNING then
            if nodes == nil then
                nodes = {}
            end
            while #env.stack > level do
                table.insert(nodes, 1, env:pop_stack())
            end
        else
            count = count + 1
        end

        last[i] = nodes
    end

    if count == #node.children then
        return bret.SUCCESS
    else
        return node:yield(env, last)
    end
end

return M
